package com.beta.cust.bind.datasync.api.response;

import com.beta.cust.bind.datasync.api.result.ResResultEnum;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.List;

@Data
@Accessors(chain = true)
public class PageResultResp<T> implements Serializable {
    @ApiModelProperty("返回码")
    private Integer code = ResResultEnum.SUCC.getCode();
    @ApiModelProperty("返回消息")
    private String msg = ResResultEnum.SUCC.getMsg();

    @ApiModelProperty("当前页，从0开始")
    private int page;
    @ApiModelProperty("每页条数")
    private int perSize;
    @ApiModelProperty("查询到的记录总条数")
    private long total;
    @ApiModelProperty("查询到的当前页的记录")
    private List<T> elements;

    @ApiModelProperty("当前页，从0开始")
    public int getNumber() {
        return page;
    }

    @ApiModelProperty("每页条数")
    public int getSize() {
        return perSize;
    }

    @ApiModelProperty("查询到的当前页的记录数")
    public int getNumberOfElements() {
        return elements == null ? 0 : elements.size();
    }

    @ApiModelProperty("查询到的当前页的记录")
    public List<T> getContent() {
        return elements;
    }

    @ApiModelProperty("当前页是否有记录")
    public boolean hasContent() {
        return getNumberOfElements() > 0;
    }

    @ApiModelProperty("查询到的记录总共多少页")
    public int getTotalPages() {
        long count = 0L;
        if (getSize() > 0) {
            count = getTotalElements() / getSize();
            if (getTotalElements() % getSize() > 0L) {
                ++count;
            }
        }
        return (int) count;
    }

    @ApiModelProperty("查询到的记录总条数")
    public long getTotalElements() {
        return total;
    }

    public boolean hasNext() {
        return getNumber() + 1 < getTotalPages();
    }

    public boolean isLast() {
        return !hasNext();
    }

    public boolean isSucc() {
        return code != null && code.intValue() == 200;
    }

    public static <T> PageResultResp<T> success(List<T> elements) {
        return result(200, "操作成功", elements);
    }

    public static <T> PageResultResp<T> failure(int code, String msg) {
        return result(200, "操作成功", null);
    }

    public static <T> PageResultResp<T> result(int code, String msg, List<T> elements) {
        PageResultResp<T> pageResp = new PageResultResp<>();
        pageResp.setCode(code);
        pageResp.setMsg(msg);
        pageResp.setElements(elements);
        return pageResp;
    }
}
